﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;

namespace Wheels.Windows
{
    public static class DataObjectExtensions
    {
#pragma warning disable 1591

        public static DataObject Duplicate(this IDataObject source)
        {
            var result = new DataObject();
            foreach (var format in source.GetFormats(false))
                result.SetData(format, source.GetData(format, false), false);
            return result;
        }

        public static Encoding GetEncoding(this IDataObject source)
        {
            var locale = source.GetData("Locale") as Stream;
            if (locale == null)
                return null;

            using (locale)
            {
                var buffer = new byte[locale.Length];
                locale.Position = 0;
                locale.Read(buffer, 0, buffer.Length);
                var lcid = BitConverter.ToInt32(buffer, 0);
                var ci = CultureInfo.GetCultureInfo(lcid);
                return Encoding.GetEncoding(ci.TextInfo.OEMCodePage);
            }
        }

        public static string GetBytesText(this IDataObject source, string format, Encoding encoding = null)
        {
            var data = source.GetData(format, false);

            if (encoding == null)
                encoding = source.GetEncoding();

            var bytes = data as byte[];
            if (bytes != null)
                return encoding.GetString(bytes);

            return null;
        }

        public static string GetStreamText(this IDataObject source, string format, Encoding encoding = null)
        {
            var data = source.GetData(format, false);

            if (encoding == null)
                encoding = source.GetEncoding();

            var stream = data as Stream;
            if (stream != null)
            {
                var result = new StreamReader(stream, encoding).ReadToEnd();
                return result.Substring(0, result.IndexOf('\0'));
            }

            return null;
        }
    }
}
